package com.gemini.web.servlet;

import com.gemini.pojo.User;
import com.gemini.service.impl.UserServiceImpl;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet("/register")
public class RegisterServlet extends HttpServlet {
    UserServiceImpl userService=new UserServiceImpl();
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String checkCode = request.getParameter("checkCode");
        String check = (String)request.getSession().getAttribute("checkCode");
        if(!checkCode.trim().equalsIgnoreCase(check)){
            request.setAttribute("register_msg","验证码错误");
            request.getRequestDispatcher("/register.jsp").forward(request,response);
            return;
        }
        User user=userService.selectUserByUsername(username);
        String register_msg,toResource;
        if(user!=null){
            register_msg="用户名已存在";
            toResource="/register.jsp";
        }else{
            userService.addUser(new User(null,username,password));
            register_msg="注册成功,请登录";
            toResource="/login.jsp";
        }
        request.setAttribute("register_msg",register_msg);
        request.getRequestDispatcher(toResource).forward(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        this.doGet(request, response);
    }
}
